#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

// 获取当前进程名（线程安全版本）
void get_process_name_safe(char* buffer, size_t size) {
    if (!buffer || size == 0) {
        return;
    }
    
    FILE* file = fopen("/proc/self/comm", "r");
    if (file) {
        if (fgets(buffer, size, file)) {
            // 去除换行符
            buffer[strcspn(buffer, "\n")] = 0;
        }
        fclose(file);
    } else {
        // 如果无法读取进程名，使用默认值
        strncpy(buffer, "unknown", size - 1);
        buffer[size - 1] = '\0';
    }
}

// 检查是否应该记录此级别的日志
int should_log_level(clog_level_t level, clog_level_t min_level) {
    return level >= min_level;
}

// 格式化输出日志到控制台（带颜色）
void print_log_to_console(const log_message_t* msg, int enable_color) {
    if (!msg) {
        return;
    }
    
    const char* level_str = get_level_string(msg->level);
    const char* color_code = "";
    const char* reset_code = "";
    
    if (enable_color) {
        reset_code = COLOR_RESET;
        switch (msg->level) {
            case CLOG_INFO:
                color_code = COLOR_INFO;
                break;
            case CLOG_DEBUG:
                color_code = COLOR_DEBUG;
                break;
            case CLOG_WARNING:
                color_code = COLOR_WARNING;
                break;
            case CLOG_ERROR:
                color_code = COLOR_ERROR;
                break;
        }
    }
    
    printf("%s[%s] [%s] [%s] %s%s\n",
           color_code, msg->timestamp, level_str, 
           msg->process_name, msg->message, reset_code);
    fflush(stdout);
}

// 创建并初始化共享日志缓存
int init_shared_log_buffer(shared_log_buffer_t* buffer, int buffer_size) {
    if (!buffer || buffer_size <= 0) {
        return -1;
    }
    
    int capacity = buffer_size / sizeof(log_message_t);
    if (capacity < 1) {
        capacity = 1;
    }
    
    buffer->messages = malloc(capacity * sizeof(log_message_t));
    if (!buffer->messages) {
        return -1;
    }
    
    buffer->capacity = capacity;
    buffer->count = 0;
    buffer->head = 0;
    buffer->last_flush = time(NULL);
    
    if (pthread_mutex_init(&buffer->mutex, NULL) != 0) {
        free(buffer->messages);
        buffer->messages = NULL;
        return -1;
    }
    
    return 0;
}

// 清理共享日志缓存
void cleanup_shared_log_buffer(shared_log_buffer_t* buffer) {
    if (!buffer) {
        return;
    }
    
    if (buffer->messages) {
        free(buffer->messages);
        buffer->messages = NULL;
    }
    
    pthread_mutex_destroy(&buffer->mutex);
    
    // 重置所有字段
    buffer->capacity = 0;
    buffer->count = 0;
    buffer->head = 0;
    buffer->last_flush = 0;
}

// 格式化日志行
int format_log_line(char* buffer, size_t buffer_size, const log_message_t* msg) {
    if (!buffer || !msg || buffer_size == 0) {
        return -1;
    }
    
    return snprintf(buffer, buffer_size, "[%s] [%s] [%s] %s\n",
                    msg->timestamp, get_level_string(msg->level), 
                    msg->process_name, msg->message);
}

// 安全的文件路径构建
int build_file_path(char* dest, size_t dest_size, const char* dir, const char* filename) {
    if (!dest || !dir || !filename || dest_size == 0) {
        return -1;
    }
    
    // 检查路径长度
    if (strlen(dir) + strlen(filename) + 2 >= dest_size) {
        return -1; // 路径太长
    }
    
    // 构建路径
    if (dir[strlen(dir) - 1] == '/') {
        snprintf(dest, dest_size, "%s%s", dir, filename);
    } else {
        snprintf(dest, dest_size, "%s/%s", dir, filename);
    }
    
    return 0;
}

// 验证配置参数的有效性
int validate_log_config(const log_config_t* config) {
    if (!config) {
        return -1;
    }
    
    // 检查日志路径
    if (strlen(config->log_path) == 0 || strlen(config->log_path) >= MAX_PATH_LEN) {
        fprintf(stderr, "Invalid log path: too long or empty\n");
        return -1;
    }
    
    // 检查文件大小限制
    if (config->max_file_size <= 0) {
        fprintf(stderr, "Invalid max file size: must be positive\n");
        return -1;
    }
    
    // 检查socket路径
    if (strlen(config->socket_path) == 0 || strlen(config->socket_path) >= MAX_PATH_LEN) {
        fprintf(stderr, "Invalid socket path: too long or empty\n");
        return -1;
    }
    
    // 检查日志级别
    if (config->min_log_level < CLOG_INFO || config->min_log_level > CLOG_ERROR) {
        fprintf(stderr, "Invalid log level: %d\n", config->min_log_level);
        return -1;
    }
    
    // 检查缓存大小
    if (config->buffer_size <= 0) {
        fprintf(stderr, "Invalid buffer size: must be positive\n");
        return -1;
    }
    
    // 检查刷新间隔
    if (config->flush_interval <= 0) {
        fprintf(stderr, "Invalid flush interval: must be positive\n");
        return -1;
    }
    
    return 0;
}
